package api;

import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.CountDownLatch;

public class ZKexist {
    String ip = "azyjz.ltd:2181";
    private ZooKeeper zooKeeper;

    @Before
    public void before() throws Exception{
        final CountDownLatch countDownLatch = new CountDownLatch(1);
        zooKeeper= new ZooKeeper(ip, 50000, new Watcher() {
            public void process(WatchedEvent event) {
                System.out.println("创建连接成功");
                countDownLatch.countDown();
            }
        });
        countDownLatch.await();
    }

    @Test
    public void exists1() throws  Exception{
        // 同步获取节点是否存在
        // arg1:节点的路径
        // arg2:watch
        // return: 返回Stat对象，若!=null,此节点存在
        Stat stat = zooKeeper.exists("/exists", false);
        if(stat!=null) {
            System.out.println(stat.getVersion());
        }
    }

    @Test
    public void exists2() throws  Exception{
        // 异步获取节点是否存在
        // arg1:节点的路径
        // arg2:节点修改的数据
        // arg3:异步回调接口
        zooKeeper.exists("/exists", false, new AsyncCallback.StatCallback() {
            public void processResult(int rc, String path, Object ctx, Stat stat) {
                // 0 判断成功
                System.out.println(rc);
                // 路径
                System.out.println(path);
                // 上下文参数
                System.out.println(ctx);
                // null 节点不存在
                System.out.println(stat.getVersion());
            }
        }, "im context");


    }

    @After
    public void after() throws InterruptedException {
        zooKeeper.close();
    }
}
